import { Models } from '../../../../common/typings/model'
import KoaRouter from 'koa-router'
import Mysql from '../../../../core/Mysql'
import httpErrors from '../../../../core/HttpException'
import { getTreeByList, lineToHumpObject, sort } from '../../../../common/utils/utils'
import Auth from '../../../../middlewares/Auth'
import Config from '../../../../config/Config'
const router = new KoaRouter({
  prefix: `${Config.api_prefix}system/role`,
})

router.get('/getRoleMap', Auth.verifyToken, async () => {
  const res = (
    await Mysql.command(`
      (SELECT
        id,
        name,
        \`describe\`,
        updated_at,
        parent_id,
        serial_num
      FROM
        role)
      ORDER BY
      updated_at DESC;

  `)
  ).results.map(lineToHumpObject)
  const records = getTreeByList(res, 0)
  const each = (arr: Models.TreeNode[]) => {
    sort(arr, 'serialNum', 'desc')
    arr.forEach((item) => {
      if (item.children) {
        each(item.children)
      }
    })
  }
  each(records)
  throw new httpErrors.Success(records)
})

export default router
